import Speech from 'speak-tts'
import { baseIp } from '@/api/config'
import axios from 'axios';

class TTS{
    constructor(){
        this.audio = new Audio()

        // 授权
        this.tok = "24.f985cc976fff86b2c19b1116e978397a.2592000.1685598089.282335-33056083";

        axios({
            'method': 'POST',
            'url': 'https://aip.baidubce.com/oauth/2.0/token?client_id=SvfzEbpCVpqOlTxHhmCqIIpY&client_secret=qPjrjNqo0OoncPS72UxGelIZLRT4PZu3&grant_type=client_credentials',
            'headers': {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
            }
        }).then(res => {
            this.tok = res.data.access_token
        })

        // 朗读文本
        this.tex = ''

        // 语速 0-15
        this.rate = 5

        // 音调 0-15
        this.pitch = 5

        // 音量 0-15
        this.vol = 5

        // 语音库
        this.per = 0
        this.pers = [
            {
                key : '小宇',
                value : 1
            },
            {
                key : '小美',
                value : 0
            },
            {
                key : '逍遥',
                value : 3
            },
            {
                key : '丫丫',
                value : 4
            }
        ]
    }
    // 获取src
    getSrc(){
        return baseIp + `/text/read?tex=${this.tex}&per=${this.per}&spd=${this.rate}&pit=${this.pitch}`
    }
    get(){
        return `https://tsn.baidu.com/text2audio?tok=${this.tok}&tex=${this.tex}&per=${this.per}&spd=${this.rate}&pit=${this.pitch}&cuid=1&ctp=1&lan=zh`
    }
    init(){
        return Promise.resolve()
    }
    // 朗读
    speak(data){
        this.tex = data.text || ''
        let listeners = data.listeners || {}
        this.audio.src = this.get()
        this.audio.play().catch(() => {
            
        })
        this.audio.onended = () => {
            if (typeof listeners.onend == 'function') {
                listeners.onend()
            }
        }
    }

    // 恢复朗读
    resume(){
        this.audio.play()
    }
    // 暂停朗读
    pause(){
        this.audio.pause()
    }
    // 关闭朗读
    cancel(){
        this.audio.pause()
        this.audio.src = ''
    }

    setLanguage(){}
}


export default {
    Speech,
    TTS
}